package han.temp;

import com.han.http.client.paramter.RequestHeader;
import han.entity.FinanceProjectFinanceEntity;
import han.entity.FinanceProjectIdEntity;
import han.exception.MuchRequestException;
import han.exception.NoneCompanyIdException;
import han.exception.UnLoginException;
import han.fetch.Fetcher;
import han.proof.Cookie;
import han.sql.Operator;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import static com.han.http.util.Print.printlnErr;
import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/7/16 13:15
 * @dscription: TODO
 */
public class FinanceExperienceFetcher implements Runnable {
    private final Operator operator;
    private final Object lock;
    private List<FinanceProjectIdEntity> entityList;
    private Cookie cookie;

    FinanceExperienceFetcher(List<FinanceProjectIdEntity> entityList, Operator operator, Cookie cookie, Object lock) {
        this.entityList = entityList;
        this.operator = operator;
        this.cookie = cookie;
        this.lock = lock;
    }

    @Override
    public void run() {

        RequestHeader[] headers = {
                new RequestHeader("Host", "rong.36kr.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Accept", "application/json, text/plain, */*"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36"),
                new RequestHeader("X-Tingyun-Id", "Dio1ZtdC5G4;r=89066499"),
                new RequestHeader("Referer", "https://rong.36kr.com/list/detail&?label=unlimited&sortField=HOT_SCORE"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie.getCookie())
        };
        List<FinanceProjectFinanceEntity> financeEntityList = new ArrayList<>();
        Random random = new Random();
        int interval;
        int count = 0;
        for (FinanceProjectIdEntity entity : entityList) {
            if (cookie.getStatus() != 0) {
                printlnInfo(cookie.getLoginName() + "不可用");
                break;
            }
            String projectId = entity.getProjectId();
            interval = random.nextInt(1000 * 10) + 1000 * 10;
            try {
                synchronized (lock) {
                    //避免同时发出大量请求
                    List<FinanceProjectFinanceEntity> tempList = getCompanyInfo(projectId, headers);
                    financeEntityList.addAll(tempList);
                    count++;
                    printlnInfo(getThreadStatus() + projectId + "获取完成," + count);
                }
            } catch (MuchRequestException e) {
                printlnErr(getThreadStatus() + cookie.getLoginName() + "可能被暂时了");
                cookie.setStatus(1);
            } catch (UnLoginException e) {
                printlnErr(getThreadStatus() + cookie.getLoginName() + "可能被永久封了");
                cookie.setStatus(2);
            } catch (NoneCompanyIdException e) {
                printlnErr(getThreadStatus() + projectId + "没有这个项目");
            } finally {
                try {
                    Thread.sleep(interval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (financeEntityList.size() >= 30) {
                //每30个下载一次
                synchronized (operator) {
                    //operator.updateFinanceInfo(financeEntityList);
                }
                financeEntityList.clear();
            }
        }
        printlnInfo(cookie.getLoginName() + "成功访问:" + count + "个链接");
    }

    private String getThreadStatus() {
        Thread thread = Thread.currentThread();
        String name = thread.getName();
        String id = thread.getId() + "";
        Thread.State state = thread.getState();
        return "<id:" + id + ",名称:" + name + ",状态:" + state + ">";
    }

    private List<FinanceProjectFinanceEntity> getCompanyInfo(String companyId, RequestHeader[] headers) throws
            MuchRequestException, NoneCompanyIdException, UnLoginException {

        Fetcher fetcher = new Fetcher();
        String url = "https://rong.36kr.com/n/api/company/" + companyId + "/finance";
        List<FinanceProjectFinanceEntity> entityList = new ArrayList<>();
        try {
            //获取数据
            String rowJsonStr = fetcher.getInfoByGet(url, headers, 1000 * 10, 1000 * 10,
                    null);
            if (rowJsonStr.contains("您请求的过于频繁，请稍后再试")) {
                throw new MuchRequestException();
            }
            if (rowJsonStr.contains("公司不存在")) {
                throw new NoneCompanyIdException();
            }
            if (rowJsonStr.contains("用户未登录")) {
                throw new UnLoginException();
            }
            rowJsonStr = rowJsonStr.replace("\n", "");
            entityList = analyzeCompanyFinance(rowJsonStr, companyId);
        } catch (MuchRequestException | NoneCompanyIdException | UnLoginException e) {
            throw e;
        } catch (Exception e) {
            printlnErr(companyId + ":解析失败" + e.getMessage());
        }

        return entityList;
    }

    /**
     * 解析融资经历
     *
     * @param finance 融资经历json字符串
     */
    private List<FinanceProjectFinanceEntity> analyzeCompanyFinance(String finance, String krId) {
        List<FinanceProjectFinanceEntity> financeEntityList = new LinkedList<>();
        JSONObject rowJson = new JSONObject(finance);
        JSONArray dataArray = rowJson.getJSONArray("data");
        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject tempJson = dataArray.getJSONObject(i);
            String amount = "无";
            try {
                //融资金额
                amount = tempJson.getString("financeAmount");
            } catch (Exception ignore) {
            }
            String amountUnit = "无";
            try {
                //货币单位
                amountUnit = tempJson.getString("financeAmountUnit");
            } catch (Exception ignore) {
            }
            Date date = new Date(System.currentTimeMillis());
            try {
                //日期
                long dateL = tempJson.getLong("financeDate");
                date = new Date(dateL);
            } catch (Exception ignore) {
            }
            String phase = "无";
            try {
                //轮次
                phase = tempJson.getString("phase");
            } catch (Exception ignore) {
            }
            StringBuilder investIdSB = new StringBuilder();
            try {
                //投资方
                JSONArray participantArray = tempJson.getJSONArray("participantVos");
                for (int j = 0; j < participantArray.length(); j++) {
                    JSONObject tempJsonObj = participantArray.getJSONObject(j);
                    String investName = tempJsonObj.getString("entityName");
                    investIdSB.append(investName).append(",");
                }
            } catch (Exception e) {
                investIdSB.append("无");
            }
            FinanceProjectFinanceEntity entity = new FinanceProjectFinanceEntity(krId, amount, amountUnit, date, phase, investIdSB.toString());
            financeEntityList.add(entity);
        }

        return financeEntityList;
    }
}
